#!/bin/bash

# 构建监控脚本 - 实时监控构建过程的系统资源使用

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m'

# 图标
CPU_ICON="🧠"
MEM_ICON="💾"
DISK_ICON="💿"
TIME_ICON="⏰"
MONITOR_ICON="📊"

echo -e "${BLUE}${MONITOR_ICON} 构建监控启动...${NC}"
echo -e "${YELLOW}按 Ctrl+C 停止监控${NC}\n"

# 创建日志文件
LOG_FILE="build-monitor-$(date +%Y%m%d_%H%M%S).log"
echo "时间,CPU使用率(%),内存使用率(%),可用内存(MB)" > $LOG_FILE

# 监控循环
while true; do
    TIMESTAMP=$(date '+%H:%M:%S')
    
    # CPU使用率 (简化版)
    CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | awk -F'%' '{print $1}' 2>/dev/null || echo "0")
    
    # 内存使用情况
    MEM_INFO=$(free | grep Mem)
    TOTAL_MEM=$(echo $MEM_INFO | awk '{print $2}')
    USED_MEM=$(echo $MEM_INFO | awk '{print $3}')
    AVAIL_MEM=$(echo $MEM_INFO | awk '{print $7}')
    
    if [ "$TOTAL_MEM" -gt 0 ]; then
        MEM_USAGE=$(echo "scale=1; $USED_MEM * 100 / $TOTAL_MEM" | bc -l 2>/dev/null || echo "0")
        AVAIL_MB=$(echo "scale=0; $AVAIL_MEM / 1024" | bc -l 2>/dev/null || echo "0")
    else
        MEM_USAGE="0"
        AVAIL_MB="0"
    fi
    
    # 颜色编码
    if (( $(echo "$CPU_USAGE > 80" | bc -l 2>/dev/null || echo 0) )); then
        CPU_COLOR=$RED
    elif (( $(echo "$CPU_USAGE > 50" | bc -l 2>/dev/null || echo 0) )); then
        CPU_COLOR=$YELLOW
    else
        CPU_COLOR=$GREEN
    fi
    
    if (( $(echo "$MEM_USAGE > 80" | bc -l 2>/dev/null || echo 0) )); then
        MEM_COLOR=$RED
    elif (( $(echo "$MEM_USAGE > 60" | bc -l 2>/dev/null || echo 0) )); then
        MEM_COLOR=$YELLOW
    else
        MEM_COLOR=$GREEN
    fi
    
    # 输出当前状态（覆盖上一行）
    printf "\r${CYAN}${TIME_ICON} %s${NC} | ${CPU_COLOR}${CPU_ICON} CPU: %s%%${NC} | ${MEM_COLOR}${MEM_ICON} 内存: %s%%${NC} | ${BLUE}${DISK_ICON} 可用: %sMB${NC}" \
           "$TIMESTAMP" "$CPU_USAGE" "$MEM_USAGE" "$AVAIL_MB"
    
    # 记录到日志
    echo "$TIMESTAMP,$CPU_USAGE,$MEM_USAGE,$AVAIL_MB" >> $LOG_FILE
    
    sleep 3
done